package ar.com.e2solver;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import ar.com.e2solver.conf.PuzzleTheme;
import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.solver.SolverResult;
import ar.com.e2solver.view.E2SolverView;

public final class Main {
	
	private Main(){}

	public static void main(String args[]) {

		try {
			if (args.length == 1 && args[0].equals("-informe")) {
				runInforme();
			}

			PuzzleTheme puzzleTheme = new PuzzleTheme();
			new E2SolverView(new E2Solver(puzzleTheme));

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	/**
	 * Itera sobre la poblacion y las iteraciones y muestra el resultado en
	 * consola con formato csv. Se usa para recolectar datos y mostrar informe.
	 * 
	 * @throws Exception
	 */
	private static void runInforme() {
		PuzzleTheme puzzleTheme;
		FileWriter fr = null;
		PrintWriter pw = null;
		
		try {
			fr = new FileWriter("/home/rodo/Documents/Facultad/Tesis/resultados/" + System.currentTimeMillis() + ".csv");
			pw = new PrintWriter(fr);
			puzzleTheme = new PuzzleTheme();
			E2Solver solver = new E2Solver(puzzleTheme);

			System.out.println(buildHeader());

			for (int i = 0; i < 3; i++) {
				for (int poblacion = 15; poblacion <= 15; poblacion += poblacion) {
					for (int iteraciones = 2000; iteraciones <= 500000; iteraciones += iteraciones) {
						solver.getSolverConfiguration().setIterations(iteraciones);
						solver.getSolverConfiguration().setPopulationNumber(poblacion);
						SolverResult result = solver.run();

						String rowStr = buildResultRow(poblacion, iteraciones, result);
						pw.println(rowStr);
						pw.flush();
						System.out.println(rowStr);
					}
				}
				System.out.println("");
			}
		} catch (BusinessException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if(pw != null){
					pw.close();
				}
				if(fr != null){
					fr.close();
				}
			} catch (IOException e) {}
		}

	}

	private static String buildResultRow(int poblacion, int iteraciones,
			SolverResult result) {

		StringBuffer sb = new StringBuffer();
		sb.append(poblacion).append(",");
		sb.append(iteraciones).append(",");
		sb.append(result.getBestIndividual().getFitnessValue()).append(",");
		sb.append(result.getAlgorithmDuration()).append(",");
		sb.append(result.getPopulationES()).append(",");
		sb.append(result.getPopulationVS()).append(",");
		sb.append(result.getMaxPossibleFitness());
		return sb.toString();
	}

	private static String buildHeader() {
		StringBuffer sb = new StringBuffer();
		sb.append("poblacion,");
		sb.append("iteraciones,");
		sb.append("bestIndividual,");
		sb.append("duration,");
		sb.append("ES,");
		sb.append("VS,");
		sb.append("MaxPossible");
		return sb.toString();
	}
}
